//
//  WHYEmoticonView.swift
//  emoticonKeyboard
//
//  Created by 王洪运 on 15/11/29.
//  Copyright © 2015年 王洪运. All rights reserved.
//

import UIKit

let WHYEmoticonViewCellID = "WHYEmoticonViewCellID"

class WHYEmoticonView: UIView {

    private var selectedEmoticonCallBack: (emoticon: WHYEmoticon) -> ()
    
// MARK: - 构造函数
    init(selectedEmoticon: (emoticon: WHYEmoticon) -> ()) {
        self.selectedEmoticonCallBack = selectedEmoticon
        
        var rect = UIScreen.mainScreen().bounds
        rect.size.height = 226
        
        super.init(frame: rect)
        
        setupUI()
        
        let indexPath = NSIndexPath(forItem: 0, inSection: 1)
//        必须将跳转到默认分组的代码放到主线程异步执行，要不不会跳转
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true)
        }
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
// MARK: - 按钮监听事件
    @objc private func clickItem (item: UIBarButtonItem) {
        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true)
    }
    
// MARK: - 懒加载子控件
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: WHYEmoticonViewLayout())
    
    private lazy var toolBar = UIToolbar()
    
    private lazy var packages = WHYEmoticonManager.sharedManager.packages
    
// MARK: - 自定义布局
    private class WHYEmoticonViewLayout: UICollectionViewFlowLayout {
        private override func prepareLayout() {
            super.prepareLayout()
            
            let col: CGFloat = 7
            let row: CGFloat = 3
            
            let w = collectionView!.bounds.width / col
            let margin = CGFloat(Int((collectionView!.bounds.height - row * w) / 2))
            
            itemSize = CGSize(width: w, height: w)
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
            
            //        注意：当 collectionView 的滚动方向是水平时，流水布局的显示是从上到下，从左至右排列的
            //                   当 collectionView 的滚动方向是垂直时，流水布局的显示是从左到右，从上至下排列的
            scrollDirection = .Horizontal
            collectionView?.pagingEnabled = true
            collectionView?.bounces = false
            collectionView?.showsHorizontalScrollIndicator = false
            
        }
    }

}

// MARK: - 设置UI
extension WHYEmoticonView {
    
    private func setupUI () {
        
        addSubview(collectionView)
        addSubview(toolBar)
        
        collectionView.snp_makeConstraints { (make) -> Void in
            make.left.top.right.equalTo(self)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self)
            make.height.equalTo(36)
        }
        
        prepareToolBar()
        prepareCollectionView()
        
    }
    
    private func prepareToolBar () {
        toolBar.backgroundColor = UIColor.darkGrayColor()
        
        var items = [UIBarButtonItem]()
        
        var index = 0
        for a in packages {
            let item = UIBarButtonItem(title: a.group_name_cn, style: .Plain, target: self, action: "clickItem:")
             item.tag = index++
            
            items.append(item)
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        }
        
        items.removeLast()
        toolBar.items = items
    }
    
    private func prepareCollectionView () {
        collectionView.backgroundColor = UIColor.whiteColor()
        
        collectionView.registerClass(WHYEmoticonCell.self, forCellWithReuseIdentifier: WHYEmoticonViewCellID)
        
        collectionView.dataSource = self
        collectionView.delegate = self
    }
    
}



// MARK: - UICollectionViewDataSource,  UICollectionViewDelegate
extension WHYEmoticonView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(WHYEmoticonViewCellID, forIndexPath: indexPath) as! WHYEmoticonCell
        
        cell.emoticon = packages[indexPath.section].emoticons[indexPath.item]
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let emoticon = packages[indexPath.section].emoticons[indexPath.item]
        selectedEmoticonCallBack(emoticon: emoticon)
        
        if indexPath.section > 0 {
            if emoticon.isEmpty != true && emoticon.isRemove != true{
                WHYEmoticonManager.sharedManager.addFavorite(emoticon)
            }
        }
    }
    
}

// MARK: - WHYEmoticonCell
private class WHYEmoticonCell: UICollectionViewCell {
    
    var emoticon: WHYEmoticon? {
        didSet {
            emoticonButton.setImage(UIImage(contentsOfFile: emoticon!.imagePath), forState: .Normal)
            emoticonButton.setTitle(emoticon?.emoji, forState: .Normal)
            
            if emoticon!.isRemove {
                emoticonButton.setImage(UIImage(contentsOfFile: emoticon!.removeImagePath), forState: .Normal)
            }
        }
    }
    
// MARK: - cell构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(emoticonButton)
        emoticonButton.backgroundColor = UIColor.whiteColor()
        emoticonButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
        emoticonButton.frame = CGRectInset(bounds, 4, 4)
        emoticonButton.titleLabel?.font = UIFont.systemFontOfSize(32)
        emoticonButton.userInteractionEnabled = false
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var emoticonButton: UIButton = UIButton()
    
}




